package com.videoplatform.service;

import com.videoplatform.entity.Video;
import com.videoplatform.repository.VideoRepository;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap; // Import HashMap
import java.util.List;
import java.util.Map; // Import Map
import java.util.Optional;
import java.util.UUID;

@Service
public class VideoService {
    
    @Autowired
    private VideoRepository videoRepository;
    
    @Value("${video.upload.dir}")
    private String uploadDir;
    
    private static final String[] ALLOWED_EXTENSIONS = {"mp4", "avi", "mov", "wmv", "flv", "webm", "mkv"};
    private static final long MAX_FILE_SIZE = 500 * 1024 * 1024; // 500MB
    
    @PostConstruct
    public void init() {
        // 创建上传目录
        try {
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
        } catch (Exception e) {
            System.err.println("无法创建上传目录: " + uploadDir + ", 错误: " + e.getMessage());
            // 使用默认目录
            uploadDir = System.getProperty("java.io.tmpdir") + "/video-uploads/";
            try {
                Path defaultPath = Paths.get(uploadDir);
                if (!Files.exists(defaultPath)) {
                    Files.createDirectories(defaultPath);
                }
            } catch (Exception ex) {
                System.err.println("无法创建默认上传目录: " + ex.getMessage());
            }
        }
    }
    
    /**
     * 上传视频文件
     */
    public Video uploadVideo(MultipartFile file, String title, String description) throws IOException {
        // 验证文件
        validateFile(file);
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        String uniqueFilename = UUID.randomUUID().toString() + "." + extension;
        
        // 保存文件
        Path filePath = Paths.get(uploadDir, uniqueFilename);
        Files.copy(file.getInputStream(), filePath);
        
        // 创建视频记录
        Video video = new Video();
        video.setTitle(title != null && !title.trim().isEmpty() ? title : originalFilename);
        video.setDescription(description);
        video.setFileName(originalFilename);
        video.setFilePath(filePath.toString());
        video.setFileSize(file.getSize());
        video.setUploadTime(LocalDateTime.now());
        video.setStatus(Video.VideoStatus.ACTIVE);
        
        return videoRepository.save(video);
    }
    
    /**
     * 验证上传文件
     */
    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new IllegalArgumentException("文件大小不能超过500MB");
        }
        
        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        
        String extension = FilenameUtils.getExtension(filename).toLowerCase();
        boolean isValidExtension = false;
        for (String allowedExt : ALLOWED_EXTENSIONS) {
            if (allowedExt.equals(extension)) {
                isValidExtension = true;
                break;
            }
        }
        
        if (!isValidExtension) {
            throw new IllegalArgumentException("不支持的文件格式，支持的格式: " + String.join(", ", ALLOWED_EXTENSIONS));
        }
    }
    
    /**
     * 获取所有活跃视频
     */
    public List<Video> getAllActiveVideos() {
        try {
            return videoRepository.findByStatusOrderByUploadTimeDesc(Video.VideoStatus.ACTIVE);
        } catch (Exception e) {
            System.err.println("获取视频列表失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }
    
    /**
     * 根据ID获取视频
     */
    public Optional<Video> getVideoById(Long id) {
        try {
            return videoRepository.findById(id);
        } catch (Exception e) {
            System.err.println("获取视频失败: " + e.getMessage());
            return Optional.empty();
        }
    }
    
    /**
     * 增加观看次数
     */
    public void incrementViewCount(Long id) {
        try {
            Optional<Video> videoOpt = videoRepository.findById(id);
            if (videoOpt.isPresent()) {
                Video video = videoOpt.get();
                video.setViewCount(video.getViewCount() + 1);
                videoRepository.save(video);
            }
        } catch (Exception e) {
            System.err.println("更新观看次数失败: " + e.getMessage());
        }
    }
    
    /**
     * 搜索视频
     */
    public List<Video> searchVideos(String keyword) {
        try {
            return videoRepository.findByTitleContainingIgnoreCase(keyword);
        } catch (Exception e) {
            System.err.println("搜索视频失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取热门视频
     */
    public List<Video> getPopularVideos() {
        try {
            return videoRepository.findAllByOrderByViewCountDesc();
        } catch (Exception e) {
            System.err.println("获取热门视频失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }
    
    /**
     * 删除视频
     */
    public boolean deleteVideo(Long id) {
        try {
            Optional<Video> videoOpt = videoRepository.findById(id);
            if (videoOpt.isPresent()) {
                Video video = videoOpt.get();
                
                // 删除文件
                try {
                    Path filePath = Paths.get(video.getFilePath());
                    Files.deleteIfExists(filePath);
                } catch (IOException e) {
                    // 记录日志但不阻止删除数据库记录
                    System.err.println("删除文件失败: " + e.getMessage());
                }
                
                // 删除数据库记录
                videoRepository.delete(video);
                return true;
            }
            return false;
        } catch (Exception e) {
            System.err.println("删除视频失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 获取视频统计信息
     */
    public Map<String, Object> getPlatformStats() {
        Map<String, Object> stats = new HashMap<>();
        try {
            long totalVideos = videoRepository.countByStatus(Video.VideoStatus.ACTIVE);
            Long totalSize = videoRepository.getTotalFileSize(Video.VideoStatus.ACTIVE);
            
            stats.put("totalVideos", totalVideos);
            stats.put("totalSize", totalSize != null ? totalSize : 0L);
            stats.put("formattedSize", getFormattedSize(totalSize != null ? totalSize : 0L));

        } catch (Exception e) {
            System.err.println("获取统计信息失败: " + e.getMessage());
            stats.put("totalVideos", 0L);
            stats.put("totalSize", 0L);
            stats.put("formattedSize", "0 B");
        }
        return stats;
    }
    
    private String getFormattedSize(long totalSize) {
        if (totalSize < 1024) {
            return totalSize + " B";
        } else if (totalSize < 1024 * 1024) {
            return String.format("%.1f KB", totalSize / 1024.0);
        } else if (totalSize < 1024 * 1024 * 1024) {
            return String.format("%.1f MB", totalSize / (1024.0 * 1024.0));
        } else {
            return String.format("%.1f GB", totalSize / (1024.0 * 1024.0 * 1024.0));
        }
    }

    // Inner class VideoStats is no longer needed as we return a Map
}

